Movie = require('../models/movie')
Category = require('../models/category')
# index page
exports.index = (req, res)->
  Category
    .find()
    .populate({
      path: 'movies',
      options: {limit:5}
    })
    .exec (err, categories)->
      console.log err if err
      res.render 'index', {
        title: '首页',
        categories: categories
      }
exports.search = (req, res)->
  catId = req.query.cat
  q = req.query.q
  console.log q
  page = parseInt(req.query.p, 10) or 0
  count = 4
  index = page*count
  if catId
    Category#查询数据库
      .find({_id: catId})
      .populate({
        path: 'movies',
        select: 'title poster'
      })
      .exec (err, categories)->
        console.log err if err
        category = categories[0] || {}
        movies = category.movies || {}#取到数据
        results = movies.slice(index, index + count)
        res.render 'results', {
          title: '结果列表页面',
          keyword: category.name,
          currentPage: (page + 1),
          query: 'cat=' + catId,
          totalPage: Math.ceil(movies.length / count),
          movies: results
        }
  else
    Movie
      .find {title: new RegExp(q+ '.*', 'i')} #i匹配大小写不敏感
      .exec (err, movies)->
        console.log err if err
        results = movies.slice(index, index + count)
        res.render 'results', {
          title: q,
          keyword: q,
          currentPage: (page + 1),
          query: 'q=' + q,
          totalPage: Math.ceil(movies.length / count),
          movies: results
        }

